############
# Polywog with PRE and POST Summonses Data
############
library(MASS)
library(polywog)
library(locfit)

rm(list=ls())
SummonsesPRE <- read.csv(file="summonsesPRE.csv",head=TRUE,sep=",")

# 1) Run polywog on the PRE data
set.seed(83)
pwPRE <- polywog(kenyatta ~ reg_1+reg_2+reg_4+reg_5+reg_6+reg_7+male+age5pt+urban+catholic+protestant+monthnum, data = SummonsesPRE, degree=2, family=c("binomial"), X=TRUE, boot=5)
	summary(pwPRE)

# 2) Collect the coefficients
coefPRE<-as.matrix(pwPRE$coefficients)

###
# Polywog is computing intensive.  If you want to skip that step, load from here
# load("[...dir...]/Kenya_polywogboot")

# 3) Insheeting manually constructed expanded data
SummonsesPOSTexp <- read.csv(file="summonsesPOSTexp.csv",head=TRUE,sep=",")
pwPOST<-as.matrix(SummonsesPOSTexp)

# 4) Making the XB values for POST data
xbPOST<-pwPOST%*%coefPRE

# 5) Taking the normal CDF of each XB value
phixbPOST<-pnorm(xbPOST)

# 6) Constructing the residual
KenPOST <- read.csv(file="summonsesPOSTken.csv",head=TRUE,sep=",")
ken<-as.matrix(KenPOST)
rPOST<-phixbPOST-ken

plot(xbPOST,rPOST, type="p", col="white", ylim = c(0.43,1),
	xlab= expression(paste("Predicted Latent Support, X",beta)), ylab = expression(paste("Difference, ", phi,"(",X,beta,")",- y)))
	fit2<-locfit(rPOST~xbPOST, family="binomial")
	lines(fit2, col="black")
